using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Toolbox.Model
{
    /// <summary>
    /// 页签状态配置
    /// </summary>
    public class TabStatus
    {
        [JsonPropertyName("name")]
        public string Name { get; set; } = "";
        
        [JsonPropertyName("className")]
        public string ClassName { get; set; } = "";
        
        [JsonPropertyName("enabled")]
        public bool Enabled { get; set; } = true;
        
        [JsonPropertyName("order")]
        public int Order { get; set; } = 0;
    }
    
    /// <summary>
    /// 页签注册管理器
    /// 负责扫描、注册和管理所有页签类
    /// </summary>
    public static class TabRegistry
    {
        private static Dictionary<string, Type> _tabTypes = new Dictionary<string, Type>();
        private static Dictionary<string, TabStatus> _tabStatuses = new Dictionary<string, TabStatus>();
        private static string _configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Conf", "TabStatus.json");
        
        /// <summary>
        /// 初始化页签注册系统
        /// </summary>
        public static void Initialize()
        {
            ScanAndRegisterTabTypes();
            LoadTabStatuses();
            // 确保配置文件存在
            SaveTabStatuses();
        }
        
        /// <summary>
        /// 扫描并注册所有页签类
        /// </summary>
        private static void ScanAndRegisterTabTypes()
        {
            _tabTypes.Clear();
            
            // 获取当前程序集
            Assembly assembly = Assembly.GetExecutingAssembly();
            
            // 查找所有继承自BaseTabPage的非抽象类
            var tabPageTypes = assembly.GetTypes()
                .Where(t => t.IsSubclassOf(typeof(BaseTabPage)) && !t.IsAbstract)
                .ToList();
            
            // 注册所有页签类型
            foreach (var type in tabPageTypes)
            {
                try
                {
                    // 创建实例以获取页签名称
                    var instance = (BaseTabPage)Activator.CreateInstance(type)!;
                    string tabName = instance.TabName;
                    
                    if (!string.IsNullOrEmpty(tabName))
                    {
                        _tabTypes[tabName] = type;
                    }
                }
                catch (Exception ex)
                {
                    // 记录错误但继续处理其他类型
                    System.Diagnostics.Debug.WriteLine($"无法注册页签类型 {type.Name}: {ex.Message}");
                }
            }
        }
        
        /// <summary>
        /// 加载页签状态配置
        /// </summary>
        private static void LoadTabStatuses()
        {
            try
            {
                if (File.Exists(_configFilePath))
                {
                    string json = File.ReadAllText(_configFilePath);
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 保留中文字符，不进行Unicode转义
                    };
                    var statuses = JsonSerializer.Deserialize<List<TabStatus>>(json, options);
                    
                    if (statuses != null)
                    {
                        _tabStatuses.Clear();
                        foreach (var status in statuses)
                        {
                            _tabStatuses[status.Name] = status;
                        }
                    }
                }
                
                // 确保所有已注册的页签都有状态配置
                EnsureAllTabsHaveStatus();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载页签状态配置失败: {ex.Message}");
                // 发生错误时，确保所有页签都有默认状态
                EnsureAllTabsHaveStatus();
            }
        }
        
        /// <summary>
        /// 确保所有已注册的页签都有状态配置
        /// </summary>
        private static void EnsureAllTabsHaveStatus()
        {
            foreach (var kvp in _tabTypes)
            {
                string tabName = kvp.Key;
                Type tabType = kvp.Value;
                
                if (!_tabStatuses.ContainsKey(tabName))
                {
                    try
                    {
                        // 创建实例以获取默认值
                        var instance = (BaseTabPage)Activator.CreateInstance(tabType)!;
                        
                        _tabStatuses[tabName] = new TabStatus
                        {
                            Name = tabName,
                            ClassName = tabType.FullName ?? tabType.Name,
                            Enabled = true,
                            Order = instance.TabOrder
                        };
                    }
                    catch
                    {
                        // 如果创建实例失败，使用默认值
                        _tabStatuses[tabName] = new TabStatus
                        {
                            Name = tabName,
                            ClassName = tabType.FullName ?? tabType.Name,
                            Enabled = true,
                            Order = 999
                        };
                    }
                }
            }
        }
        
        /// <summary>
        /// 保存页签状态配置
        /// </summary>
        public static void SaveTabStatuses()
        {
            try
            {
                // 确保目录存在
                string? directory = Path.GetDirectoryName(_configFilePath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 保留中文字符，不进行Unicode转义
                };
                
                string json = JsonSerializer.Serialize(_tabStatuses.Values.ToList(), options);
                File.WriteAllText(_configFilePath, json);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存页签状态配置失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 获取所有已启用的页签实例，按顺序排序
        /// </summary>
        /// <returns>已启用的页签实例列表</returns>
        public static List<BaseTabPage> GetEnabledTabs()
        {
            var enabledTabs = new List<BaseTabPage>();
            
            // 获取所有已启用的页签状态，按顺序排序
            var sortedStatuses = _tabStatuses.Values
                .Where(s => s.Enabled)
                .OrderBy(s => s.Order)
                .ToList();
            
            // 创建对应的页签实例
            foreach (var status in sortedStatuses)
            {
                if (_tabTypes.TryGetValue(status.Name, out Type? tabType))
                {
                    try
                    {
                        var instance = (BaseTabPage)Activator.CreateInstance(tabType)!;
                        enabledTabs.Add(instance);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"无法创建页签实例 {status.Name}: {ex.Message}");
                    }
                }
            }
            
            return enabledTabs;
        }
        
        /// <summary>
        /// 获取所有已注册的页签信息
        /// </summary>
        /// <returns>页签信息列表</returns>
        public static List<BaseTabPage> GetAllTabs()
        {
            var allTabs = new List<BaseTabPage>();
            
            // 获取所有页签状态，按顺序排序
            var sortedStatuses = _tabStatuses.Values
                .OrderBy(s => s.Order)
                .ToList();
            
            // 创建对应的页签实例
            foreach (var status in sortedStatuses)
            {
                if (_tabTypes.TryGetValue(status.Name, out Type? tabType))
                {
                    try
                    {
                        var instance = (BaseTabPage)Activator.CreateInstance(tabType)!;
                        allTabs.Add(instance);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"无法创建页签实例 {status.Name}: {ex.Message}");
                    }
                }
            }
            
            return allTabs;
        }
        
        /// <summary>
        /// 刷新页签状态（当页签启用/禁用状态改变时调用）
        /// </summary>
        public static void RefreshTabs()
        {
            // 重新加载页签状态配置
            LoadTabStatuses();
        }
        
        /// <summary>
        /// 获取所有页签状态
        /// </summary>
        /// <returns>所有页签状态列表</returns>
        public static List<TabStatus> GetAllTabStatuses()
        {
            return _tabStatuses.Values.ToList();
        }
        
        /// <summary>
        /// 更新页签状态
        /// </summary>
        /// <param name="tabStatus">页签状态</param>
        public static void UpdateTabStatus(TabStatus tabStatus)
        {
            _tabStatuses[tabStatus.Name] = tabStatus;
            SaveTabStatuses();
        }
        
        /// <summary>
        /// 获取页签类型
        /// </summary>
        /// <param name="tabName">页签名称</param>
        /// <returns>页签类型，如果不存在则返回null</returns>
        public static Type? GetTabType(string tabName)
        {
            _tabTypes.TryGetValue(tabName, out Type? tabType);
            return tabType;
        }
        
        /// <summary>
        /// 获取所有已启用的页签名称
        /// </summary>
        /// <returns>已启用的页签名称列表</returns>
        public static List<string> GetEnabledTabNames()
        {
            return _tabStatuses.Values
                .Where(s => s.Enabled)
                .Select(s => s.Name)
                .ToList();
        }
        
        /// <summary>
        /// 设置页签启用/禁用状态
        /// </summary>
        /// <param name="tabName">页签名称</param>
        /// <param name="enabled">是否启用</param>
        public static void SetTabEnabled(string tabName, bool enabled)
        {
            if (_tabStatuses.TryGetValue(tabName, out TabStatus? status))
            {
                status.Enabled = enabled;
                SaveTabStatuses();
            }
        }
        
        /// <summary>
        /// 获取所有已注册的页签名称
        /// </summary>
        /// <returns>页签名称列表</returns>
        public static List<string> GetAllTabNames()
        {
            return _tabTypes.Keys.ToList();
        }
    }
}